local H = require "packages/new_heg/util"
local U = require "packages/utility/utility"
local extension = Package:new("stable")
extension.extensionName = "new_heg_diy"
extension.game_modes_whitelist = { 'mul_heg_mode', 'ex_heg_mode' }

Fk:loadTranslationTable{
  ["stable"] = "日月交辉·固",
  ["wk_heg"] = "日月",
}

--- 治流递归
---@param room Room
---@param player ServerPlayer
---@param num integer
local function AskForContinueZhiliu(room, player, num)
  local targets = table.map(table.filter(room.alive_players, function (p) return p ~= player end), Util.IdMapper)
  local tos, id = room:askForChooseCardsAndPlayers(player, num, num, targets, 1, 1, nil, "#wk_heg__zhiliu-give:::"..num, "wk_heg__zhiliu", true)
  if #tos > 0 then
    room:obtainCard(tos[1], id, false, fk.ReasonGive)
    local to = room:getPlayerById(tos[1])
    room:setPlayerMark(player, "wk_heg__zhiliu-turn", 1)
    if to:getMark("wk_heg__zhiliu-turn") == 0 then
      AskForContinueZhiliu(room, to, num + 1)
    end
  end
end

local jiakui = General(extension, "wk_heg__jiakui", "wei", 3, 3, General.Male)
local zhiliu = fk.CreateTriggerSkill{
  name = "wk_heg__zhiliu",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Play and not player:isNude()
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    AskForContinueZhiliu(room, player, 1)
  end,
}

--- 交换主副将
---@param room Room
---@param player ServerPlayer
---@return boolean
local function SwapMainAndDeputy(room, player)
  local general1 = player.general
  local general2 = player.deputyGeneral
  if not (general1 and general2) then return false end
  if general1 == "anjiang" then player:revealGeneral(false, true) end
  if general2 == "anjiang" then player:revealGeneral(true, true) end
  general1 = player.general
  general2 = player.deputyGeneral
  if string.find(general1, "lord") 
   or string.find(general1, "zhonghui") or string.find(general1, "simazhao") 
   or string.find(general1, "sunchen") or string.find(general1, "gongsunyuan") 
  then return false end
  room:changeHero(player, "blank_shibing", false, true, false, false, false)
  room:changeHero(player, general2, false, false, true, false, false)
  room:changeHero(player, general1, false, true, true, false, false)
  return true
end

local zhengbi = fk.CreateTriggerSkill{
  name = "wk_heg__dingwang__zhengbi",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
      and (table.find(player:getCardIds(Player.Hand), function(id) return Fk:getCardById(id).type == Card.TypeBasic end) or table.every(player.room:getOtherPlayers(player), function(p) return H.getGeneralsRevealedNum(p) == 0 end))
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choices = {}
    local basic_cards1 = table.filter(player:getCardIds(Player.Hand), function(id)
      return Fk:getCardById(id).type == Card.TypeBasic end)
    local targets1 = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return H.getGeneralsRevealedNum(p) > 0 end), Util.IdMapper)
    local targets2 = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return H.getGeneralsRevealedNum(p) == 0 end), Util.IdMapper)
    if #basic_cards1 > 0 and #targets1 > 0 then
      table.insert(choices, "zhengbi_giveCard")
    end
    if #targets2 > 0 then
      table.insert(choices, "zhengbi_useCard")
    end
    if #choices == 0 then return false end
    local choice = room:askForChoice(player, choices, self.name)
    if choice:startsWith("zhengbi_giveCard") then
      local tos, id = room:askForChooseCardAndPlayers(player, targets1, 1, 1, ".|.|.|.|.|basic", "#ld__zhengbi-give", self.name, true)
      room:obtainCard(tos[1], id, false, fk.ReasonGive)
      local to = room:getPlayerById(tos[1])
      if to.dead or to:isNude() then return end
      local cards2 = to:getCardIds("he")
      if #cards2 > 1 then
        local card_choices = {}
        local num = #table.filter(to:getCardIds(Player.Hand), function(id)
          return Fk:getCardById(id).type == Card.TypeBasic end)
        if num > 1 then
          table.insert(card_choices, "zhengbi__basic-back:"..player.id)
        end
        if #to:getCardIds("he") - num > 0 then
          table.insert(card_choices, "zhengbi__nobasic-back:"..player.id)
        end
        if #card_choices == 0 then return false end
        local card_choice = room:askForChoice(to, card_choices, self.name)
        if card_choice:startsWith("zhengbi__basic-back") then
          cards2 = room:askForCard(to, 2, 2, false, self.name, false, ".|.|.|.|.|basic", "#ld__zhengbi-give1:"..player.id)
        elseif card_choice:startsWith("zhengbi__nobasic-back") then
          cards2 = room:askForCard(to, 1, 1, true, self.name, false, ".|.|.|.|.|^basic", "#ld__zhengbi-give2:"..player.id)
        end
      end
      room:moveCardTo(cards2, Player.Hand, player, fk.ReasonGive, self.name, nil, false, player.id)
    elseif choice:startsWith("zhengbi_useCard") then
      local tos2 = room:askForChoosePlayers(player, targets2, 1, 1, "#ld__zhengbi_choose", self.name, true)
      if #tos2 then
        room:setPlayerMark(room:getPlayerById(tos2[1]), "@@ld__zhengbi_choose-turn", 1)
      end
    end
  end,

  refresh_events = {fk.GeneralRevealed},
  can_refresh = function(self, event, target, player, data)
    return player:hasSkill(self) and target:getMark("@@ld__zhengbi_choose-turn") > 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(target, "@@ld__zhengbi_choose-turn", 0)
  end,
}

local zhengbi_targetmod = fk.CreateTargetModSkill{
  name = "#wk_heg__dingwang__zhengbi_targetmod",
  frequency = Skill.Compulsory,
  bypass_times = function(self, player, skill, scope, card, to)
    return card and player:hasSkill(zhengbi) and to:getMark("@@ld__zhengbi_choose-turn") > 0
  end,
  bypass_distances =  function(self, player, skill, card, to)
    return card and player:hasSkill(zhengbi) and to:getMark("@@ld__zhengbi_choose-turn") > 0
  end,
}

local huibian = fk.CreateActiveSkill{
  name = "wk_heg__dingwang__huibian",
  anim_type = "control",
  target_num = 2,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    if #selected == 0 then
      local target2 = Fk:currentRoom():getPlayerById(to_select)
      return target2.kingdom == "wei"
    elseif #selected == 1 then
      local target1 = Fk:currentRoom():getPlayerById(to_select)
      return target1.kingdom == "wei" and target1:isWounded()
    else
      return false
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target1 = room:getPlayerById(effect.tos[1])
    local target2 = room:getPlayerById(effect.tos[2])
    room:damage{
      from = player,
      to = target1,
      damage = 1,
      skillName = self.name,
    }
    if not target1.dead then
      target1:drawCards(2, self.name)
    end
    if not target2.dead and target2:isWounded() then
      room:recover{
        who = target2,
        num = 1,
        recoverBy = player,
        skillName = self.name
      }
    end
  end,
}

local fangzhu = fk.CreateTriggerSkill{
  name = "wk_heg__dingwang__fangzhu",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#hs__fangzhu-choose:::"..player:getLostHp(), self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local num = player:getLostHp()
    if to.hp > 0 and #room:askForDiscard(to, num, num, true, self.name, true, nil, "hs__fangzhu_ask:::" .. num, false) > 0 then
      if not to.dead then room:loseHp(to, 1, self.name) end
    else
      to:drawCards(num, self.name)
      if not to.dead then to:turnOver() end
    end
  end,
}

local dingwang = fk.CreateTriggerSkill{
  name = "wk_heg__dingwang",
  anim_type = "drawcard",
  relate_to_place = "m",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player == target and player.phase == Player.Start and player.hp < player.maxHp
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player, "wk_heg__dingwang", 1)
    if player:getMark("wk_heg__dingwang") == 1 then
      local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#wk_heg__dingwang__zhengbi-choose", self.name, true)
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        room:handleAddLoseSkills(to, "wk_heg__dingwang__zhengbi", nil)
      end
    elseif player:getMark("wk_heg__dingwang") == 2 then
      local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#wk_heg__dingwang__huibian-choose", self.name, true)
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        if to:hasSkill("wk_heg__dingwang__zhengbi") or to:hasSkill("ld__zhengbi") then
          if to:hasSkill("ld__zhengbi") and not to:hasSkill("wk_heg__dingwang__zhengbi") then
            room:handleAddLoseSkills(to, "-ld__zhengbi", nil)
          end
          if to:hasSkill("wk_heg__dingwang__zhengbi") then
            room:handleAddLoseSkills(to, "-wk_heg__dingwang__zhengbi", nil)
          end
          room:handleAddLoseSkills(to, "wk_heg__dingwang__huibian", nil)
        end
      end
    elseif player:getMark("wk_heg__dingwang") == 3 then
      local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#wk_heg__dingwang__fangzhu-choose", self.name, true)
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        if to:hasSkill("wk_heg__dingwang__huibian") or to:hasSkill("huibian") then
          if to:hasSkill("huibian") and not to:hasSkill("wk_heg__dingwang__huibian") then
            room:handleAddLoseSkills(to, "-huibian", nil)
          end
          if to:hasSkill("wk_heg__dingwang__huibian") then
            room:handleAddLoseSkills(to, "-wk_heg__dingwang__huibian", nil)
          end
          room:handleAddLoseSkills(to, "wk_heg__dingwang__fangzhu", nil)
        end
      end
    else
      local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1, "#wk_heg__dingwang__swap-choose", self.name, true)
      if #tos > 0 then
        local to = room:getPlayerById(tos[1])
        SwapMainAndDeputy(room, to)
      end
    end
  end
}

local wanlan = fk.CreateTriggerSkill{
  name = "wk_heg__wanlan",
  anim_type = "drawcard",
  relate_to_place = "d",
  events = {fk.EnterDying},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player ~= target
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:throwAllCards("h")
    room:recover({
      who = target,
      num = 1 - target.hp,
      recoverBy = player,
      skillName = self.name,
    })
    SwapMainAndDeputy(room, player)
  end,
}

zhengbi:addRelatedSkill(zhengbi_targetmod)
jiakui:addRelatedSkill(zhengbi)
jiakui:addRelatedSkill(huibian)
jiakui:addRelatedSkill(fangzhu)
jiakui:addSkill(zhiliu)
jiakui:addSkill(dingwang)
jiakui:addSkill(wanlan)
jiakui:addCompanions("hs__n_caopi")
Fk:loadTranslationTable{
  ["wk_heg__jiakui"] = "贾逵", --魏国
  ["designer:wk_heg__jiakui"] = "静谦&教父&小作坊",
  ["#wk_heg__jiakui"] = "",

  ["wk_heg__zhiliu"] = "治流",
  [":wk_heg__zhiliu"] = "出牌阶段开始时，你可将一张牌交给一名其他角色，然后若以此法获得牌的角色本回合未以此法失去过牌，其可以重复牌数+1的此流程。",
  ["wk_heg__dingwang"] = "定王",
  [":wk_heg__dingwang"] = "主将技，准备阶段，若你已受伤，你可令一名角色执行第X项：1.获得【征辟】；2.失去【征辟】获得【挥鞭】；3.失去【挥鞭】获得【放逐】；>3.交换主副将（X为此技能发动次数）。",
  ["wk_heg__wanlan"] = "挽澜",
  [":wk_heg__wanlan"] = "副将技，其他角色进入濒死状态时，你可弃置所有手牌，令其回复体力至1点，然后你交换主副将。",

  ["wk_heg__dingwang__huibian"] = "挥鞭",
  [":wk_heg__dingwang__huibian"] = "出牌阶段限一次，你可选择一名魏势力角色和另一名已受伤的魏势力角色，若如此做，你对前者造成1点伤害，令其摸两张牌，然后后者回复1点体力。",
  ["wk_heg__dingwang__zhengbi"] = "征辟",
  [":wk_heg__dingwang__zhengbi"] = "出牌阶段开始时，你可选择一项：1.选择一名没有势力的角色，直至其确定势力或此回合结束，你对其使用牌无距离与次数限制；2.将一张基本牌交给一名已确定势力的角色，然后其交给你一张非基本牌或两张基本牌。",
  ["wk_heg__dingwang__fangzhu"] = "放逐",
  [":wk_heg__dingwang__fangzhu"] = "当你受到伤害后，你可令一名其他角色选择一项：1.摸X张牌并叠置；2.弃置X张牌并失去1点体力。（X为你已损失的体力值）",

  ["#wk_heg__dingwang__zhengbi-choose"] = "定王：选择一名角色，令其获得【征辟】",
  ["#wk_heg__dingwang__huibian-choose"] = "定王：选择一名角色，若其拥有【征辟】，令其失去【征辟】获得【挥鞭】",
  ["#wk_heg__dingwang__fangzhu-choose"] = "定王：选择一名角色，若其拥有【挥鞭】，令其失去【挥鞭】获得【放逐】",
  ["#wk_heg__dingwang__swap-choose"] = "定王：选择一名角色，令其交换主副将",
  ["#wk_heg__zhiliu-give"] = "治流：你可以交给一名其他角色 %arg 牌，然后其可重复此流程",

  ["~wk_heg__jiakui"] = "",
}


local wangji = General(extension, "wk_heg__wangji", "wei", 3, 3, General.Male)
local qizhi = fk.CreateTriggerSkill{
  name = "wk_heg__qizhi",
  anim_type = "offensive",
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if not (player:hasSkill(self) and target == player.room.current and H.compareKingdomWith(player, target)) then return false end
    local room = player.room
    local damage_event = room.logic:getCurrentEvent()
    if not damage_event then return false end
    local x = target:getMark("wk_heg__qizhi-turn")
    if x == 0 then
      room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function (e)
        local reason = e.data[3]
        if reason == "damage" then
          local first_damage_event = e:findParent(GameEvent.Damage)
          if first_damage_event and first_damage_event.data[1].from == target then
            x = first_damage_event.id
            room:setPlayerMark(target, "wk_heg__qizhi-turn", x)
            return true
          end
        end
      end, Player.HistoryTurn)
    end
    return damage_event.id == x
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return p ~= data.to and not p:isNude() end), Util.IdMapper)
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__qizhi-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if self.cost_data then
      local to = room:getPlayerById(self.cost_data)
      local id = room:askForCardChosen(player, to, "he", self.name)
      room:throwCard(id, self.name, to, player)
      if not to.dead then
        to:drawCards(1, self.name)
      end
    end
  end,
}

local jinqu = fk.CreateTriggerSkill{
  name = "wk_heg__jinqu",
  anim_type = "drwacard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0  then
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason ~= fk.ReasonUse and move.moveReason ~= fk.ReasonResonpse then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
    if #targets == 0 then return end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__jinqu-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data then
      local to = room:getPlayerById(self.cost_data)
      to:drawCards(2, self.name)
      local turn_event = room.logic:getCurrentEvent():findParent(GameEvent.Turn, false)
      if turn_event == nil then return false end
      local end_id = turn_event.id
      local cards = {}
      U.getEventsByRule(room, GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.DiscardPile then
            for _, info in ipairs(move.moveInfo) do
              local card_suit = Fk:getCardById(info.cardId, true).suit
              if room:getCardArea(info.cardId) == Card.DiscardPile and not table.contains(cards, card_suit) and card_suit ~= 0 then
                table.insertIfNeed(cards, card_suit)
              end
            end
          end
        end
        return false
      end, end_id)
      local discard_num = to:getHandcardNum() - #cards
      if discard_num > 0 then
        room:askForDiscard(to, discard_num, discard_num, false, self.name, false)
      end
    end
  end,
}

wangji:addSkill(qizhi)
wangji:addSkill(jinqu)
Fk:loadTranslationTable{
  ["wk_heg__wangji"] = "王基", --魏国
  ["designer:wk_heg__wangji"] = "教父&修功",

  ["wk_heg__qizhi"] = "奇制",
  [":wk_heg__qizhi"] = "与你势力相同的角色于其回合内首次造成伤害后，你可以弃置不为受伤角色的一张牌，然后以此法失去牌的角色摸一张牌。",
  ["wk_heg__jinqu"] = "进趋",
  [":wk_heg__jinqu"] = "每回合限一次，当你不因使用或打出而失去牌后，你可令一名与你势力相同的角色摸两张牌，然后其将手牌弃至X张（X为此回合进入弃牌堆的牌花色数）。",

  ["#wk_heg__qizhi-choose"] = "奇制：选择一名除受伤角色外的角色，弃置其一张牌",
  ["#wk_heg__jinqu-choose"] = "进趋：选择一名与你势力相同的角色，令其摸两张牌",

  ["$wk_heg__qizhi1"] = "声东击西，敌寇一网成擒。",
  ["$wk_heg__qizhi2"] = "吾意不在此地，已遣别部出发。",
  ["$wk_heg__jinqu1"] = "建上昶水城，以逼夏口！",
  ["$wk_heg__jinqu2"] = "通川聚粮，伐吴之业，当步步为营。",
  ["~wk_heg__wangji"] = "天下之势，必归大魏，可恨，未能得见呐！",
}

--- 借调 （需要修复和变更的兼容）
---@param room Room
---@param player ServerPlayer
---@param target ServerPlayer
---@param deputyName string
---@param kingdom string
---@param isDeputy boolean
local function DoGiveDeputy(room, player, target, deputyName, kingdom, isDeputy)
  local orig_before = isDeputy and (player.deputyGeneral or "") or player.general
  orig_before = Fk.generals[orig_before]
  local orig_skills_before = orig_before and orig_before:getSkillNameList() or {}
  -- H.removeGeneral(room, player, isDeputy)

  player:setMark("CompanionEffect", 0)
  player:setMark("HalfMaxHpLeft", 0)
  player:doNotify("SetPlayerMark", json.encode{ player.id, "CompanionEffect", 0})
  player:doNotify("SetPlayerMark", json.encode{ player.id, "HalfMaxHpLeft", 0})
  player:revealGeneral(isDeputy, true) -- 先摆
  if room.logic:trigger("fk.GeneralRemoving", player, isDeputy) then return false end
  local orig = isDeputy and (player.deputyGeneral or "") or player.general
  if orig:startsWith("blank_") then return false end
  orig = Fk.generals[orig]
  local orig_skills = orig and orig:getSkillNameList() or {}
  local new_general = orig.gender == General.Male and "blank_shibing" or "blank_nvshibing"
  orig_skills = table.map(orig_skills, function(e)
    return "-" .. e
  end)
  room:handleAddLoseSkills(player, table.concat(orig_skills, "|"), nil, false)
  if isDeputy then
    room:setPlayerProperty(player, "deputyGeneral", new_general)
    room:setPlayerMark(player, "__heg_deputy", new_general)
  else
    room:setPlayerProperty(player, "general", new_general)
    room:setPlayerMark(player, "__heg_general", new_general)
  end
  player:filterHandcards()
  room:sendLog{
    type = "#GeneralRemoved",
    from = player.id,
    arg = isDeputy and "deputyGeneral" or "mainGeneral",
    arg2 = orig.name,
  }
  -- room:returnToGeneralPile({orig.name})
  room.logic:trigger("fk.GeneralRemoved", player, orig.name)

  room:handleAddLoseSkills(target, table.concat(orig_skills_before, "|"), nil, false)
  room:setPlayerMark(target, "@wk_give_deputy", deputyName)
  room:setPlayerMark(target, "@wk_give_deputy_kingdom", kingdom)
end

--- 结束借调
---@param room Room
---@param player ServerPlayer
---@param skillName string
local function StopGiveDeputy(room, player, skillName)
  local orig_string = player:getMark("@wk_give_deputy")
  local orig = Fk.generals[orig_string]
  room:returnToGeneralPile({orig_string})
  local orig_skills = orig and orig:getSkillNameList() or {}
  orig_skills = table.map(orig_skills, function(e)
    return "-" .. e
  end)
  room:handleAddLoseSkills(player, table.concat(orig_skills, "|"), nil, false)

  local targets = table.map(table.filter(room.alive_players, function(p)
    return p.kingdom == player:getMark("@wk_give_deputy_kingdom") 
    and (p.deputyGeneral:startsWith("blank_") or p.general:startsWith("blank_")) end), Util.IdMapper)
  if #targets > 0 then
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#wk_give_deputy-choose", skillName, false)
    if #to > 0 then
      local target = room:getPlayerById(to[1])
      local choices = {}
      if target.deputyGeneral:startsWith("blank_") then
        table.insert(choices, "wk_give_deputy_back")
      end
      if target.general:startsWith("blank_") then
        table.insert(choices, "wk_give_main_back")
      end
      if #choices > 0 then
        local choice = room:askForChoice(player, choices, skillName)
        if choice == "wk_give_deputy_back" then
          room:changeHero(target, orig_string, false, true, true, false, false)
          room.logic:trigger("fk.GeneralTransformed", target, orig_string)
        else
          room:changeHero(target, orig_string, false, false, true, false, false)
          room.logic:trigger("fk.GeneralTransformed", target, orig_string)
        end
      end
    end
  end

  room:setPlayerMark(player, "@wk_give_deputy", 0)
  room:setPlayerMark(player, "@wk_give_deputy_kingdom", 0)
end

Fk:loadTranslationTable{
  ["@wk_give_deputy"] = "借调",
  ["@wk_give_deputy_kingdom"] = "属国",

  ["#wk_give_deputy-choose"] = "借调：选择该借调武将牌原所属国家一名有士兵牌的角色，结束借调并返还此武将牌于其",
}

local jianyong = General(extension, "wk_heg__jianyong", "shu", 3, 3, General.Male)
local youxiang = fk.CreateActiveSkill{
  name = "wk_heg__youxiang",
  anim_type = "special",
  target_num = 1,
  can_use =function (self, player, card, extra_data)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function (self, to_select, selected, selected_cards, card, extra_data, player)
    return #selected == 0 and to_select ~= player.id and H.compareKingdomWith(player, Fk:currentRoom():getPlayerById(to_select), true)
      and player:canPindian(Fk:currentRoom():getPlayerById(to_select))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local pindian = player:pindian({target}, self.name)
    if player.dead or target.dead then return end
    if pindian.results[target.id].winner == player then
      local all_choices = {target.general, target.deputyGeneral}
      local disable_choices = {}
      if not (target.general ~= "anjiang" and not target.general:startsWith("blank_") and not string.find(target.general, "lord")) then -- 耦合君主
        table.insert(disable_choices, target.general)
      end
      if not (target.deputyGeneral ~= "anjiang" and not target.deputyGeneral:startsWith("blank_")) then
        table.insert(disable_choices, target.deputyGeneral)
      end
      if #disable_choices == 2 then return false end
      local result = room:askForCustomDialog(target, self.name,
        "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
          all_choices,
          {"OK"},
          "#wk_heg__youxiang-ask::" .. player.id,
          {},
          1,
          1,
          disable_choices
        })
        local choice
        if result ~= "" then
          local reply = json.decode(result)
          choice = reply.cards[1]
        else
          choice = table.find(all_choices, function(g)
            return not table.contains(disable_choices, g)
          end)
        end
        local isDeputy = choice == target.deputyGeneral
        DoGiveDeputy(room, target, player, choice, target.kingdom, isDeputy)
        room:setPlayerMark(player, "wk_give_deputy_jianyong", 1)
        room:setPlayerMark(player, "wk_heg__youxiang-record", choice)
    else
      if not player:isKongcheng() then
        local mcards, max = {}, -1
        for _, cid in ipairs(player:getCardIds("h")) do
          local c = Fk:getCardById(cid)
          if c.number > max then
            mcards = {cid}
            max = c.number
          elseif c.number == max then
            table.insert(mcards, cid)
          end
        end
        local card, _ = U.askforChooseCardsAndChoice(target, mcards, {"OK"}, self.name, "#wk_heg__youxiang-get", nil, 1, 1, player:getCardIds("h"))
        room:obtainCard(target, card, true, fk.ReasonPrey, target.id, self.name)
        end
    end
  end,
}

local youxiang_delay = fk.CreateTriggerSkill{
  name = "#wk_heg__youxiang_delay",
  anim_type = "special",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return player == target and player:getMark("wk_give_deputy_jianyong") == 1 and player:getMark("@wk_give_deputy") == player:getMark("wk_heg__youxiang-record")
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    StopGiveDeputy(player.room, player, self.name)
    player.room:setPlayerMark(player, "wk_give_deputy_jianyong", 0)
    player.room:setPlayerMark(player, "wk_heg__youxiang-record", 0)
  end,
}

local zongshi = fk.CreateTriggerSkill{
  name = "wk_heg__zongshi",
  anim_type = "defensive",
  frequency = Skill.Compulsory,
  events = {fk.BeforeTurnOver, fk.DamageInflicted},
  can_trigger = function (self, event, target, player, data)
    if player ~= target or not player:hasSkill(self) then return end
    if event == fk.BeforeTurnOver then
      return true
    else
      return player.chained and data.damageType ~= fk.NormalDamage
    end
  end,
  on_use = function (self, event, target, player, data)
    if event == fk.BeforeTurnOver then
      return true
    else
      data.damage = data.damage - 1
    end
  end,
}
jianyong:addCompanions("hs__n_liubei")
youxiang:addRelatedSkill(youxiang_delay)
jianyong:addSkill(youxiang)
jianyong:addSkill(zongshi)
Fk:loadTranslationTable{
  ["wk_heg__jianyong"] = "简雍",
  ["designer:wk_heg__jianyong"] = "",
  ["wk_heg__youxiang"] = "游降",
  [":wk_heg__youxiang"] = "出牌阶段限一次，你可以与一名与你势力不同的角色拼点，若你：赢，其借调一张其已明置的武将牌于你至此回合结束；没赢，其观看你所有手牌并获得其中点数最大的一张。",
  ["wk_heg__zongshi"] = "纵适",
  [":wk_heg__zongshi"] = "锁定技，当你叠置时，取消之；当你受到属性伤害时，若你横置，此伤害-1。",
  ["#wk_heg__youxiang_delay"] = "游降",

  ["#wk_heg__youxiang-ask"] = "游降：选择一张武将牌借调给 %dest",
  ["#wk_heg__youxiang-get"] = "游降：选择一张点数最大的牌获得",

  ["$wk_heg__youxiang1"] = "合则两利，斗则两伤。",
  ["$wk_heg__youxiang2"] = "君且安坐，听我一言。",
  ["$wk_heg__zongshi1"] = "买卖不成，情义还在。",
  ["$wk_heg__zongshi2"] = "此等小事，何须挂耳？",
  ["~wk_heg__jianyong"] = "两国交战……不斩……",
}


local maliang = General(extension, "wk_heg__maliang", "shu", 3, 3, General.Male)
local zishu = fk.CreateTriggerSkill{
  name = "wk_heg__zishu",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.BeforeCardUseEffect, fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    if event == fk.BeforeCardUseEffect then
      return player:hasSkill(self) and player.room.current == player and data.tos and data.card.type ~= Card.TypeEquip
    else
      -- if not (player:hasSkill(self) and player.room.current ~= player) then return false end
      -- local cardInfo = {}
      -- for _, move in ipairs(data) do
      --   if move.to and move.to == player.id and move.toArea == Card.PlayerHand then
      --     for _, info in ipairs(move.moveInfo) do
      --       table.insert(cardInfo, info.cardId)
      --     end
      --   end
      -- end
      -- if #cardInfo > 0 then
      --   self.cost_data = cardInfo
      --   return true
      -- end
      return player:hasSkill(self) and target ~= player and table.find(player.player_cards[Player.Hand], function (id)
        return Fk:getCardById(id):getMark("@@zishu-inhand") > 0
      end)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.BeforeCardUseEffect then
      local id_tos = TargetGroup:getRealTargets(data.tos)
      if #id_tos > 1 then
        local tos = room:askForChoosePlayers(player, id_tos, #id_tos, #id_tos, "#wk_heg__zishu_choose", self.name, false)
        local new_tos = {}
        for _, id in ipairs(tos) do
          for _, info in ipairs(data.tos) do
            if info[1] == id then
              table.insert(new_tos, info)
              break
            end
          end
        end
        data.tos = new_tos
      end
      local draw_card = false
      for _, info in ipairs(data.tos) do
        if info[1] == player.id then
          draw_card = true
          break
        end
      end
      if draw_card then
        player:drawCards(1, self.name)
      end
    else
      -- if #self.cost_data > 0 then
      --   room:throwCard(self.cost_data, self.name, player, player)
      -- end
      for _, id in ipairs(player:getCardIds(Player.Hand)) do
        if Fk:getCardById(id):getMark("@@zishu-inhand") > 0 then
          table.insert(cards, id)
        end
      end
      if #cards > 0 then
        room:moveCards({
          from = player.id,
          ids = cards,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonPutIntoDiscardPile,
          skillName = self.name,
          proposer = player.id,
        })
      end
    end
  end,

  refresh_events = {fk.AfterCardsMove, fk.AfterTurnEnd},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      return player:hasSkill(self, true) and player.room.current ~= player
    else
      table.find(player.player_cards[Player.Hand], function (id)
        return Fk:getCardById(id):getMark("@@zishu-inhand") > 0
      end)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Player.Hand then
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            if room:getCardArea(id) == Card.PlayerHand and room:getCardOwner(id) == player then
              room:setCardMark(Fk:getCardById(id), "@@zishu-inhand", 1)
            end
          end
        end
      end
    elseif event == fk.AfterTurnEnd then
      for _, id in ipairs(player:getCardIds(Player.Hand)) do
        room:setCardMark(Fk:getCardById(id), "@@zishu-inhand", 0)
      end
    end
  end,
}

local xiemu = fk.CreateActiveSkill{
  name  = "wk_heg__xiemu",
  anim_type = "support",
  prompt = "wk_heg__xiemu_prompt",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and #table.filter(Fk:currentRoom().alive_players, function (p) return p:getMark("_wk_heg__xiemu-turn") > 0 end) > 0
  end,
  card_num = 1,
  card_filter = function(self, to_select, selected)
    return #selected < 1 and Fk:getCardById(to_select).suit == Card.Heart
  end,
  target_num = 0,
  target_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local card = effect.cards
    local tos = table.filter(room:getAlivePlayers(false), function (p) return p:getMark("_wk_heg__xiemu-turn") > 0 end)
    room:useVirtualCard("amazing_grace", card, player, tos, self.name)
    tos = table.map(tos, Util.IdMapper)
    room:sortPlayersByAction(tos)
    for _, pid in ipairs(tos) do
      local p = room:getPlayerById(pid)
      if not p.dead then
        U.askForPlayCard(room, p, nil, ".", self.name, "wk_heg__xiemu_use", {bypass_times = true})
      end
    end
  end,
}

local xiemuRecorder = fk.CreateTriggerSkill{
  name = "#wk_heg__xiemu_recorder",
  visible = false,
  refresh_events = {fk.TargetConfirmed, fk.EventAcquireSkill},
  can_refresh = function(self, event, target, player, data)
    if not (player:hasSkill(xiemu) or player:isFakeSkill(xiemu)) then return false end
    return (event == fk.TargetConfirmed and data.from == player.id) or (target == player and data == xiemu)
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirmed then
      room:setPlayerMark(target, "_wk_heg__xiemu-turn", 1)
    elseif room:getTag("RoundCount") then
      room.logic:getEventsOfScope(GameEvent.UseCard, 99, function (e)
        local use = e.data[1]
        if use.from == player.id then
          for _, pid in ipairs(TargetGroup:getRealTargets(use.tos)) do
            local p = room:getPlayerById(pid)
            if p:getMark("_wk_heg__xiemu-turn") == 0 then
              room:setPlayerMark(p, "_wk_heg__xiemu-turn", 1)
            end
          end
        end
      end, Player.HistoryTurn)
    end
  end,
}
maliang:addSkill(zishu)
xiemu:addRelatedSkill(xiemuRecorder)
maliang:addSkill(xiemu)
Fk:loadTranslationTable{
  ["wk_heg__maliang"] = "马良",
  ["designer:wk_heg__maliang"] = "24&教父",
  ["#wk_heg__maliang"] = "",
  ["cv:wk_heg__maliang"] = "",

  ["wk_heg__zishu"] = "自书",
  [":wk_heg__zishu"] = "锁定技，①你的回合内，所有角色使用的非装备牌由你重新指定结算顺序，然后若此牌目标包含你，你摸一张牌；②其他角色的回合结束时，你将手牌中所有本回合获得的牌置入弃牌堆。",
  ["wk_heg__xiemu"] = "协穆",
  [":wk_heg__xiemu"] = "出牌阶段限一次，你可以将一张♥牌当【五谷丰登】对本回合所有成为过你使用牌的目标使用，然后这些角色可以依次使用一张牌。",
  
  ["#wk_heg__zishu_choose"] = "自书：你可以重新指定此牌的结算顺序",
  ["wk_heg__xiemu_prompt"] = "协穆：你可以将一张红桃牌当【五谷丰登】对本回合成为过你是使用牌的目标使用",
  ["wk_heg__xiemu_use"] = "协穆：你可以使用一张牌",
  ["@@zishu-inhand"] = "自书",
  
  ["~wk_heg__maliang"] = "",
}

--- 推举
---@param room Room
---@param player ServerPlayer
---@param skillName string
---@return ServerPlayer?
local function DoElectedChange(room, player, skillName)
  local kingdom = player:getMark("__heg_kingdom")
  if kingdom == "wild" then
    kingdom = player:getMark("__heg_init_kingdom")
  end
  local generals = room:findGenerals(function(g)
    return Fk.generals[g].kingdom == kingdom or Fk.generals[g].subkingdom == kingdom
  end, 1)
  local general = room:askForGeneral(player, generals, 1, true) ---@type string
  room:sendLog{
    type = "#ElectedChangeLog",
    from = player.id,
    arg = general,
    arg2 = skillName,
    toast = true,
  }
  local targets = table.map(table.filter(room.alive_players, function(p) return H.compareKingdomWith(p, player) end), Util.IdMapper)
  room:sortPlayersByAction(targets)
  local ret
  for _, pid in ipairs(targets) do
    local p = room:getPlayerById(pid)
    local choices = {"Cancel"}
    if p.general ~= "anjiang" and not p.general:startsWith("ld__lord") and not general.subkingdom then
      table.insert(choices, "#elected_change_main:::" .. general)
    end
    if p.deputyGeneral ~= "anjiang" then
      table.insert(choices, "#elected_change_deputy:::" .. general)
    end
    local choice = room:askForChoice(p, choices, "ElectedChange", "#elected_change-ask:" .. player.id .. "::" .. general)
    if choice ~= "Cancel" then
      if choice:startsWith("#elected_change_main") then
        generals = {H.getActualGeneral(p, false)}
        room:changeHero(p, general, false, false, true, false, false)
        room.logic:trigger("fk.GeneralTransformed", p, general)
      else
        generals = {H.getActualGeneral(p, true)}
        room:changeHero(p, general, false, true, true, false, false)
        room.logic:trigger("fk.GeneralTransformed", p, general)
      end
      ret = p
      break
    end
  end
  room:returnToGeneralPile(generals)
  return {ret, general}
end

local guyong = General(extension, "wk_heg__guyong", "wu", 3, 3, General.Male)
local yanjie = fk.CreateTriggerSkill{
  name = "wk_heg__yanjie",
  anim_type = "special",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    if not (player:hasSkill(self) and player == target and player.phase == Player.Play and data.tos and table.find(TargetGroup:getRealTargets(data.tos), function(id) return id == player.id end)) then return false end
    local events = player.room.logic:getEventsOfScope(GameEvent.UseCard, 2, function(e)
      local use = e.data[1]
      return use.from == player.id and table.contains(TargetGroup:getRealTargets(use.tos), player.id)
    end, Player.HistoryPhase)
    return #events == 1
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(room.alive_players, Util.IdMapper)
    local tos = room:askForChoosePlayers(player, targets, 1, 1, "#wk_heg__yanjie-choose", self.name)
    if #tos > 0 then
      local to = room:getPlayerById(tos[1])
      local cards = room:askForDiscard(to, 1, 1, true, self.name, false, nil, "#wk_heg__yanjie-discard")
      if Fk:getCardById(cards[1]).type == data.card.type then
        if H.compareKingdomWith(to, player) then
          local choices = {"wk_heg__yanjie_doelected", "wk_heg__yanjie_usecard"}
          local choice = room:askForChoice(to, choices, self.name)
          if choice == "wk_heg__yanjie_usecard" then
            room:useVirtualCard("ex_nihilo", nil, to, to, self.name)
          else
            DoElectedChange(room, to, self.name)
          end
        else
          room:useVirtualCard("ex_nihilo", nil, to, to, self.name)
        end
      end
    end
  end,
}

local mowei = fk.CreateTriggerSkill{
  name = "wk_heg__mowei",
  anim_type = "control",
  events = {fk.TargetSpecified, fk.DamageInflicted},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    local room = player.room
    if not (player:hasSkill(self) and player == target) then return false end 
    if event == fk.TargetSpecified then
      room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
        for _, move in ipairs(e.data) do
          if move.toArea == Card.PlayerHand and move.to then
            local to = room:getPlayerById(move.to)
            if to and to:getMark("_wk_heg__mowei_record-turn") == 0 then
              for _, info in ipairs(move.moveInfo) do
                if to:getMark("_wk_heg__mowei_record-turn") == 0 then
                  room:setPlayerMark(to, "_wk_heg__mowei_record-turn", 1)
                end
              end
            end
          end
        end
        return false
      end, Player.HistoryTurn)
      -- return data.firstTarget
      return true
    else
      local events = room.logic:getEventsOfScope(GameEvent.UseCard, 1, function(e)
        local use = e.data[1]
        return use.from == player.id
      end, Player.HistoryTurn)
      return #events > 0
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.DamageInflicted then
      data.damage = data.damage - 1
    else
      local targets = table.filter(room.alive_players, function(p) return p:getMark("_wk_heg__mowei_record-turn") ~= 0 end)
      if #targets > 0 then
        data.disresponsiveList = data.disresponsiveList or {}
        for _, p in ipairs(targets) do
          table.insertIfNeed(data.disresponsiveList, p.id)
        end
      end
    end
  end,
}

guyong:addSkill(yanjie)
guyong:addSkill(mowei)
guyong:addCompanions("hs__n_zhangzhaozhanghong")
Fk:loadTranslationTable{
  ["wk_heg__guyong"] = "顾雍", --吴国
  ["designer:wk_heg__guyong"] = "静谦&635",
  ["wk_heg__yanjie"] = "严诫",
  [":wk_heg__yanjie"] = "当你于出牌阶段内首次对自己使用牌结算后，你可令一名角色弃置一张牌，若这两张牌类型相同，其视为使用【无中生有】，若其与你势力相同，其可改为推举。",
  ["wk_heg__mowei"] = "默威",
  [":wk_heg__mowei"] = "锁定技，当你受到伤害时，若你于此回合内使用过牌，此伤害-1；当你使用牌指定目标后，你令此牌不能被所有此回合获得过牌的角色响应。",

  ["#wk_heg__yanjie-choose"] = "严诫：选择一名角色，令其弃置一张牌",
  ["#wk_heg__yanjie-discard"] = "严诫：请弃置一张牌，若与使用牌类型相同，你视为使用【无中生有】",

  ["wk_heg__yanjie_doelected"] = "推举",
  ["wk_heg__yanjie_usecard"] = "视为使用【无中生有】",

  ["$wk_heg__yanjie1"] = "",
  ["$wk_heg__yanjie2"] = "",
  ["$wk_heg__mowei1"] = "",
  ["$wk_heg__mowei2"] = "",
  ["~wk_heg__guyong"] = "",
}

local sunru = General(extension, "wk_heg__sunru", "wu", 3, 3, General.Female)
local chishi = fk.CreateTriggerSkill{
  name = "wk_heg__chishi",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardsMove, fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.AfterCardsMove then
      local cardTo = -99
      local cardInfo = {}
      for _, move in ipairs(data) do
        if move.from and move.from == player.id and move.to and move.to ~= player.id and move.toArea == Card.PlayerHand then
          for _, info in ipairs(move.moveInfo) do
            table.insert(cardInfo, info.cardId)
          end
          cardTo = move.to
        end
      end
      if #cardInfo > 0 and cardTo ~= -99 then
        self.cost_data = {cardInfo, cardTo}
        return true
      end
    else
      return player:hasSkill(self) and H.compareKingdomWith(target, player) and data.to == Player.Discard
       and (target:getMark("@!yinyangfish") > 0 or target:getMark("@!companion") > 0 or target:getMark("@!vanguard") > 0 or target:getMark("@!wild") > 0)
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardsMove then
      if #self.cost_data > 0 then
        local to = room:getPlayerById(self.cost_data[2])
        room:throwCard(self.cost_data[1], self.name, to, to)
      end
    else
      data.to = Player.Play
    end
  end,
}

local xiecui = fk.CreateTriggerSkill{
  name = "wk_heg__xiecui",
  anim_type = "defensive",
  events = {fk.DamageInflicted, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if event == fk.Damaged then
      return player:hasSkill(self) and data.damageType ~= fk.NormalDamage and target:getMark("@!yinyangfish") == 0
    else
      return player:hasSkill(self) and player == target
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      return room:askForSkillInvoke(player, self.name, nil, "wk_heg__xiecui_getfish")
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      H.addHegMark(room, target, "yinyangfish")
    else
      data.damageType = fk.FireDamage
    end
  end,
}
sunru.hidden = true
sunru:addSkill(chishi)
sunru:addSkill(xiecui)
sunru:addCompanions("hs__n_luxun")
Fk:loadTranslationTable{
  ["wk_heg__sunru"] = "孙茹", --吴国
  ["designer:wk_heg__sunru"] = "老猫&教父",
  ["wk_heg__xiecui"] = "撷翠",
  [":wk_heg__xiecui"] = "一名角色受到属性伤害后，若其没有“阴阳鱼”标记，你可令其获得一个“阴阳鱼”标记；你造成的伤害均为火焰伤害。",
  ["wk_heg__chishi"] = "持室",
  [":wk_heg__chishi"] = "与你势力相同的角色可以移去一个国战标记，将弃牌阶段改为出牌阶段；当你的牌被其他角色获得后，其弃置之。",

  -- ["wk_heg__xiecui_defense"] = "撷翠：你可以令其移去一个“阴阳鱼”标记，此伤害-1",
  -- ["wk_heg__xiecui_getfish"] = "撷翠：你可以令其获得一个“阴阳鱼”标记",
  -- ["#wk_heg__chishi_discard"] = "持室：你可以弃置至多体力上限数张牌，令当前回合角色本回合手牌上限增加等量值",

  ["$wk_heg__xiecui1"] = "",
  ["$wk_heg__xiecui2"] = "",
  ["$wk_heg__chishi1"] = "",
  ["$wk_heg__chishi2"] = "",
  ["~wk_heg__sunru"] = "",
}

local guofeng = General(extension, "wk_heg__guotufengji", "qun", 3, 3, General.Male)
local jigong = fk.CreateTriggerSkill{
  name = "wk_heg__jigong",
  anim_type = "special",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player.phase == Player.RoundStart
  end,
  on_use = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "wk_heg__jigong-turn", 1)
  end,
}
local jigong_after = fk.CreateTriggerSkill{
  name = "#wk_heg__jigong_after",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseStart, fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    if not (player == target and player:usedSkillTimes(jigong.name, Player.HistoryTurn) > 0) then return false end
    if event == fk.EventPhaseChanging then
      return (data.to == Player.Start or data.to == Player.Judge or data.to == Player.Draw 
       or data.to == Player.Play or data.to == Player.Discard or data.to == Player.Finish) and player:getMark("wk_heg__jigong-turn") > 0
    else
      return player.phase == Player.Play and #player:getCardIds("he") > 0
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseChanging then
      data.to = Player.Play
    else
      room:loseHp(player, 1, self.name)
      local use = U.askForUseVirtualCard(player.room, player, "duel", nil, self.name, nil, false, false, false, false, nil, true)
      if use then
        room:useCard(use)
      end
    end
  end,

  refresh_events = {fk.Damage},
  can_refresh = function(self, event, target, player, data)
    return player == target and player:getMark("wk_heg__jigong-turn") > 0
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "wk_heg__jigong-turn", 0)
  end,
}

local wk_heg__ningjie_card_skill = fk.CreateActiveSkill{
  name = "wk_heg__ningjie_card_skill",
  prompt = "#dismantlement_skill",
  can_use = Util.CanUse,
  target_num = 1,
  mod_target_filter = function(self, to_select, selected, user, card)
    local player = Fk:currentRoom():getPlayerById(to_select)
    return user ~= to_select and not player:isAllNude()
  end,
  target_filter = function(self, to_select, selected, _, card, extra_data)
    return Util.TargetFilter(self, to_select, selected, _, card, extra_data) and
      self:modTargetFilter(to_select, selected, Self, card)
  end,
  on_effect = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.to)
    if from.dead or to.dead or to:isAllNude() then return end
    local cid = room:askForCardChosen(from, to, "hej", self.name)
    room:throwCard({cid}, self.name, to, from)
  end
}
wk_heg__ningjie_card_skill.cardSkill = true

local ningjie = fk.CreateTriggerSkill{
  name = "wk_heg__ningjie",
  anim_type = "special",
  events = {fk.TargetConfirmed},
  frequency = Skill.Compulsory,
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.room.current ~= player and data.card:isCommonTrick() and data.is_damage_card
  end,
  on_use = function (self, event, target, player, data)
    if player:getHandcardNum() == 0 then
      player:drawCards(player.maxHp, self.name)
    else
      data.extra_data = data.extra_data or {}
      data.extra_data.wk_heg__ningjieTos = data.extra_data.wk_heg__ningjieTos or {}
      local id_tos = AimGroup:getAllTargets(data.tos)
      for _, pid in ipairs(id_tos) do
        table.insertIfNeed(data.extra_data.wk_heg__ningjieTos, pid)
      end
    end
  end
}

local ningjie_effect = fk.CreateTriggerSkill{
  name = "#wk_heg__ningjie_effect",
  anim_type = "special",
  events = {fk.PreCardEffect},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return data.to and data.extra_data and data.extra_data.wk_heg__ningjieTos and table.contains(data.extra_data.wk_heg__ningjieTos, data.to)
  end,
  on_trigger = function(self, event, target, player, data)
    local card = data.card:clone()
    local c = table.simpleClone(data.card)
    for k, v in pairs(c) do
      card[k] = v
    end
    card.skill = wk_heg__ningjie_card_skill
    data.card = card
  end,
}

jigong:addRelatedSkill(jigong_after)
guofeng:addSkill(jigong)
ningjie:addRelatedSkill(ningjie_effect)
guofeng:addSkill(ningjie)
Fk:addSkill(wk_heg__ningjie_card_skill)
Fk:loadTranslationTable{
  ["wk_heg__guotufengji"] = "郭图逢纪", --吴国
  ["designer:wk_heg__guotufengji"] = "教父&小曹神",
  ["wk_heg__jigong"] = "急攻",
  [":wk_heg__jigong"] = "回合开始时，你可令你本回合所有阶段均改为出牌阶段直至你造成伤害，且本回合出牌阶段开始时，你失去1点体力并视为使用一张【决斗】。",
  ["wk_heg__ningjie"] = "佞解",
  [":wk_heg__ningjie"] = "锁定技，当你于回合外成为伤害类锦囊牌的目标后，你令此牌对所有目标角色的效果改为【过河拆桥】，若你没有手牌，则改为你将手牌摸至体力上限。",
  
  ["#wk_heg__ningjie_effect"] = "佞解",
  ["wk_heg__ningjie_card_skill"] = "佞解",
  ["#wk_heg__jigong_after"] = "急攻",

  ["$wk_heg__jigong1"] = "",
  ["$wk_heg__jigong2"] = "",
  ["$wk_heg__ningjie1"] = "",
  ["$wk_heg__ningjie2"] = "",
  ["~wk_heg__guotufengji"] = "",
}

--- 获得战策
---@param room Room
---@param player ServerPlayer
---@param num integer
---@param skillName string
local function GetPolicy(room, player, num, skillName)
  local all_policies = { "drum_together", "backarm_stop", "other_replace", "reverse_attack", "trueaim_another", "buy_arm",
          "move_insecret", "getlive_indeath", "attack_infire", "replace_something", "move_people", "getchance_insmall"}
  for _, p in ipairs(room.alive_players) do
    for _, s in ipairs(p.player_skills) do
      if table.contains(all_policies, s.name) then
        table.removeOne(all_policies, s.name)
      end
    end
  end
  local count = num
  if #all_policies < num then count = #all_policies end
  if count == 0 then return end
  local policies = table.random(all_policies, count)
  for i = 1, #policies, 1 do
    room:handleAddLoseSkills(player, policies[i], nil, false)
    U.setPrivateMark(player, policies[i].."_mark", { "@["..policies[i].."_mark]" })
  end  
  room:doBroadcastNotify("ShowToast", Fk:translate(player.general) .. '/' .. Fk:translate(player.deputyGeneral) .. " " .. Fk:translate("#PolicyGet") .. " " .. Fk:translate(num) .. " " ..Fk:translate("#PolicyCard"))
  room:sendLog{
    type = "#GetPolicyLog",
    from = player.id,
    arg = count,
    arg2 = skillName,
  }
end

local chengong = General(extension, "wk_heg__chengong", "qun", 3, 3, General.Male)
local lunduan = fk.CreateTriggerSkill{
  name = "wk_heg__lunduan",
  anim_type = "special",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.card.trueName == "slash" and player.room.current == target
     and H.compareKingdomWith(player, target) and not data.damageDealt
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    GetPolicy(room, target, 1, self.name)
    local choices = {"wk_heg__lunduan_endturn", "wk_heg__lunduan_slash_more"}
    local choice = room:askForChoice(target, choices, self.name)
    if choice == "wk_heg__lunduan_endturn" then
      room:endTurn()
    else
      room:addPlayerMark(target, MarkEnum.SlashResidue.."-turn", 1)
      room:addPlayerMark(target, MarkEnum.MinusMaxCardsInTurn, 1)
    end
  end,
}

local xuqi = fk.CreateTriggerSkill{
  name = "wk_heg__xuqi",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {"fk.HegLosePolicy"},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data[1] ~= player
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}

local xuqi_buff = fk.CreateAttackRangeSkill{
  name = "#wk_heg__xuqi_buff",
  within_func = function (self, from, to)
    for _, p in ipairs(Fk:currentRoom().alive_players) do
      if p:hasSkill(xuqi.name) and from ~= p and H.compareKingdomWith(from, p) and p:inMyAttackRange(to) then
        return true
      end
    end
  end,
}

xuqi:addRelatedSkill(xuqi_buff)
chengong:addSkill(xuqi)
chengong:addSkill(lunduan)
Fk:loadTranslationTable{
  ["wk_heg__chengong"] = "陈宫",
  ["designer:wk_heg__chengong"] = "静谦&教父",
  ["wk_heg__lunduan"] = "论断",
  [":wk_heg__lunduan"] = "与你势力相同的角色于其回合内使用【杀】结算后，若此牌未造成伤害，你可令其获得一张“战策”并选择一项：1.结束此回合；2.本回合使用【杀】次数上限+1且手牌上限-1。",
  ["wk_heg__xuqi"] = "虚栖",
  [":wk_heg__xuqi"] = "锁定技，①其他角色发动“战策”后，你摸一张牌；②你攻击范围内的角色视为处于所有与你势力相同角色的攻击范围内。",
  ["#wk_heg__xuqi_buff"] = "虚栖",

  ["wk_heg__lunduan_endturn"] = "结束此回合",
  ["wk_heg__lunduan_slash_more"] = "本回合使用【杀】次数上限+1",


  ["~wk_heg__chengong"] = "",
}

local zhanghua = General(extension, "wk_heg__zhanghua", "wild", 3, 3, General.Male)
zhanghua:addSkill("bihun")
zhanghua:addSkill("jianhe")
zhanghua:addSkill("chuanwu")

Fk:loadTranslationTable{
  ["wk_heg__zhanghua"] = "张华·活动",

  ["~wk_heg__chengong"] = "",
}

--[[
local huangquan = General(extension, "wk_heg__huangquan", "shu", 3, 3, General.Male)
local choujin = fk.CreateTriggerSkill{
  name = "wk_heg__chouji",
}
local guijue = fk.CreateTriggerSkill{
  name = "wk_heg__guijue",
}
huangquan.subkingdom = "wei"
huangquan.hidden = true
huangquan:addSkill(choujin)
huangquan:addSkill(guijue)
Fk:loadTranslationTable{
  ["wk_heg__huangquan"] = "黄权", 
  ["designer:wk_heg__huangquan"] = "",
  ["wk_heg__choujin"] = "筹进",
  [":wk_heg__choujin"] = "锁定技，①当你的攻击范围增加后，你对一名你攻击范围外的角色造成1点伤害；②你的额定摸牌数为你的攻击范围。",
  ["wk_heg__guijue"] = "归绝",
  [":wk_heg__guijue"] = "当你受到伤害后，你可弃置一个区域内所有牌并将手牌摸至三张，若你未以此法摸牌，你回复1点体力。",

  ["~wk_heg__huanquan"] = "",
}

local huanjie = General(extension, "wk_heg__huanjie", "wu", 3, 3, General.Male)
huanjie.subkingdom = "wei"
huanjie.hidden = true
local lishuo = fk.CreateTriggerSkill{
  name = "wk_heg__lishuo",
}
local jiuling = fk.CreateTriggerSkill{
  name = "wk_heg__jiuling"
}
huanjie:addSkill(lishuo)
huanjie:addSkill(jiuling)
Fk:loadTranslationTable{
  ["wk_heg__huanjie"] = "桓玠",
  ["designer:wk_heg__huanjie"] = "",
  
  ["wk_heg__jiuling"] = "柩灵",
  [":wk_heg__jiuling"] = "其他角色死亡时，你可移动其装备区内的一张牌，然后其可执行一次【英魂】的效果。",
  ["wk_heg__lishuo"] = "礼朔",
  [":wk_heg__lishuo"] = "当你受到伤害后，你可令一名角色弃置其装备区内一种颜色的所有牌，然后若其以此法弃置的牌颜色为：红色，其回复1点体力；黑色，其将手牌调整至其体力上限（至多五张）。",

  ["~wk_heg__huanjie"] = "",
}

local qianzhao = General(extension, "wk_heg__qianzhao", "wei", 4, 4, General.Male)
qianzhao.subkingdom = "qun"
local weifu = fk.CreateTriggerSkill{
  name = "wk_heg__weifu",
}
qianzhao:addSkill(weifu)
qianzhao.hidden = true
Fk:loadTranslationTable{
  ["wk_heg__qianzhao"] = "牵招",
  ["designer:wk_heg__qianzhao"] = "",

  ["wk_heg__weifu"] = "威抚",
  [":wk_heg__weifu"] = "锁定技，①你于回合内对本回合响应过你使用牌的其他角色使用牌无距离与次数限制；②当你于回合外造成伤害后，受伤角色选择是否交给你一张牌并回复1点体力。",

  ["~wk_heg__qianzhao"] = "",
}

local yongkai = General(extension, "wk_heg__yongkai", "shu", 3, 3, General.Male)
yongkai.subkingdom = "wu"
local xiaosi = fk.CreateTriggerSkill{
  name = "wk_heg__xiaosi",
}

local huba = fk.CreateTriggerSkill{
  name = "wk_heg__huba"
}
yongkai:addSkill(xiaosi)
yongkai:addSkill(huba)
yongkai.hidden = true
Fk:loadTranslationTable{
  ["wk_heg__yongkai"] = "雍恺",
  ["designer:wk_heg__yongkai"] = "",
  
  ["wk_heg__xiaosi"] = "嚣肆",
  [":wk_heg__xiaosi"] = "锁定技，①横置状态与你不同的角色使用牌使用牌指定你为目标后/成为你使用牌的目标时，此牌结算两次/取消之；②你使用牌指定目标后，你令此牌不能被所有横置的目标角色响应，然后你与所有未横置的目标角色横置。",
  ["wk_heg__huba"] = "惚跋",
  [":wk_heg__huba"] = "当你横置后，你可摸X张牌（X为处于横置状态角色数）；其他角色的出牌阶段开始时，若你与其均横置，你可以弃置一张黑色非基本牌，对其造成1点雷电伤害。",

  ["~wk_heg__yongkai"] = "",
}

local yanyan = General(extension, "wk_heg__yanyanf", "shu", 4, 4, General.Male)
yanyan.subkingdom = "qun"
local juzhan = fk.CreateTriggerSkill{
  name = "wk_heg__juzhan",
}

yanyan.hidden = true
yanyan:addSkill(juzhan)
Fk:loadTranslationTable{
  ["wk_heg__yanyanf"] = "严颜", --吴国
  ["designer:wk_heg__yanyanf"] = "",
  ["wk_heg__juzhan"] = "拒战",
  [":wk_heg__juzhan"] = "隐藏技能。",

  ["$wk_heg__juzhan1"] = "",
  ["$wk_heg__juzhan2"] = "",
  ["~wk_heg__yanyan"] = "",
}

local liuzan = General(extension, "wk_heg__liuzan", "wu", 4, 4, General.Male)
local fenyin = fk.CreateTriggerSkill{
  name = "wk_heg__fenyin",
}
liuzan.subkingdom = "qun"
liuzan.hidden = true
Fk:loadTranslationTable{
  ["wk_heg__liuzan"] = "留赞",
  ["designer:wk_heg__liuzan"] = "",
  ["wk_heg__fenyin"] = "奋音",
  [":wk_heg__fenyin"] = "隐藏技能。",
  
  ["~wk_heg__liuzan"] = "",
}


--[[--
local zhongyao = General(extension, "wk_heg__zhongyao", "wei", 3)
local chengqi = fk.CreateTriggerSkill{
  name = "wk_heg__chengqi",
  anim_type = "special",
  events = {fk.AfterCardTargetDeclared},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and data.from == player.id and (data.card.type == Card.TypeBasic or data.card:isCommonTrick())
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = TargetGroup:getRealTargets(data.tos)
    local chooses = table.map(room.alive_players, Util.IdMapper)
    local tos, id = room:askForChooseCardAndPlayers(player, chooses, 1, #targets, ".|.|spade|.|.|.", "#wk_heg__chengqi-choose", self.name, true)
    if #tos ~= 0 then
      self.cost_data = {tos, id}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    data.tos = {}
    local to = self.cost_data[1]
    local id = self.cost_data[2]
    room:throwCard({id}, self.name, player, player)
    for i = 1, #to, 1 do
      TargetGroup:pushTargets(data.tos, to[i])
    end
  end,
}

local xunzuo = fk.CreateTriggerSkill{
  name = "wk_heg__xunzuo",
  anim_type = "special",
  events = {fk.EventPhaseStart},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and H.compareKingdomWith(player, target) and H.getGeneralsRevealedNum(target) == 2 
     and target.phase == Player.Finish and target:getMark("@wk_heg__xunzuo") == 0
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local skills = {}
    local general = Fk.generals[target.general]
    local deputy = Fk.generals[target.deputyGeneral]
    for _, s in ipairs(general:getSkillNameList()) do
      if target:hasSkill(s) then
        table.insert(skills, s)
      end
    end
    for _, s in ipairs(deputy:getSkillNameList()) do
      if target:hasSkill(s) then
        table.insert(skills, s)
      end
    end
    local choice_lose = room:askForChoice(target, skills, self.name)
    room:handleAddLoseSkills(target, "-"..choice_lose, nil)

    local all_choices = {"wk_heg__hs__yiji", "wk_heg__quhu", "wk_heg__hs__weimu", "wk_heg__ld__qice", "wk_heg__wk_heg__choulue"}
    local choices = {}
    local skills = {}
    for _, p in ipairs(room.alive_players) do
      for _, s in ipairs(p.player_skills) do
        table.insert(skills, s.name)
      end
    end
    for _, skill in ipairs(all_choices) do
      local skillNames = {skill, skill:sub(9)}
      local can_choose = true
      for _, sname in ipairs(skills) do
        if table.contains(skillNames, sname) then
          can_choose = false
          break
        end
      end
      if can_choose then table.insert(choices, skill) end
    end
    if #choices == 0 then return false end
    local result = room:askForCustomDialog(target, self.name,
    "packages/utility/qml/ChooseSkillBox.qml", {
      choices, 1, 1, "#wk_heg__xunzuo-choice"
    })
    if result == "" then return false end
    local choice = json.decode(result)[1]
    room:handleAddLoseSkills(target, choice, nil)
    room:setPlayerMark(target, "@wk_heg__xunzuo", choice)
    -- room:setPlayerMark(target, "_heg__BattleRoyalMode_ignore", 1)
  end,
}

local choulueXZ = fk.CreateTriggerSkill{
  name = "wk_heg__wk_heg__choulue",
  anim_type = "offensive",
  events = {fk.Damaged, fk.TargetSpecified},
  can_trigger = function (self, event, target, player, data)
    if event == fk.Damaged then
      return player == target and player:hasSkill(self) and player:getMark("@!yinyangfish") < player.maxHp
    else
      return player:hasSkill(self) and H.compareKingdomWith(player, target) and #AimGroup:getAllTargets(data.tos) == 1
        and data.card:isCommonTrick() and player:getMark("@!yinyangfish") ~= 0
    end
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, event == fk.Damaged and "#wk_heg__choulue-getfish" or "#wk_heg__choulue-twice")
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      H.addHegMark(room, player, "yinyangfish")
    else
      room:removePlayerMark(player, "@!yinyangfish")
      if player:getMark("@!yinyangfish") == 0 then
        player:loseFakeSkill("yinyangfish_skill&")
      end
      data.additionalEffect = 1
    end
  end,
}

local weimuXZ = fk.CreateTriggerSkill{
  name = "wk_heg__hs__weimu",
  anim_type = "defensive",
  events = { fk.TargetConfirming, fk.BeforeCardsMove },
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.TargetConfirming then
      return target == player and data.card.color == Card.Black and data.card:isCommonTrick()
    elseif event == fk.BeforeCardsMove then
      local id = 0
      local source = player
      local room = player.room
      local c
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerJudge then
          for _, info in ipairs(move.moveInfo) do
            id = info.cardId
            if info.fromArea == Card.PlayerJudge then
              source = room:getPlayerById(move.from) or player
            else
              source = player
            end
            c = source:getVirualEquip(id)
            --FIXME：巨大隐患，延时锦囊的virtual_equips在置入判定区的事件被篡改，或者判定阶段自然流程以外的方式离开判定区时不会清理
            if not c then c = Fk:getCardById(id) end
            if c.sub_type == Card.SubtypeDelayedTrick and c.color == Card.Black then
              return true
            end
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetConfirming then
      AimGroup:cancelTarget(data, player.id)
      return true
    elseif event == fk.BeforeCardsMove then
      local source = player
      local mirror_moves = {}
      local ids = {}
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerJudge then
          local move_info = {}
          local mirror_info = {}
          for _, info in ipairs(move.moveInfo) do
            local id = info.cardId
            if info.fromArea == Card.PlayerJudge then
              source = room:getPlayerById(move.from) or player
            else
              source = player
            end
            local c = source:getVirualEquip(id)
            if not c then c = Fk:getCardById(id) end
            if c.sub_type == Card.SubtypeDelayedTrick and c.color == Card.Black then
              table.insert(mirror_info, info)
              table.insert(ids, id)
            else
              table.insert(move_info, info)
            end
          end
          if #mirror_info > 0 then
            move.moveInfo = move_info
            local mirror_move = table.clone(move)
            mirror_move.to = nil
            mirror_move.toArea = Card.DiscardPile
            mirror_move.moveInfo = mirror_info
            table.insert(mirror_moves, mirror_move)
          end
        end
      end
      table.insertTable(data, mirror_moves)
    end
  end,
}

local qiceXZ = fk.CreateActiveSkill{
  name = "wk_heg__ld__qice",
  prompt = "#ld__qice-active",
  interaction = function()
    local handcards = Self:getCardIds(Player.Hand)
    local names, all_names = {} , {}
    for _, id in ipairs(Fk:getAllCardIds()) do
      local card = Fk:getCardById(id)
      if card:isCommonTrick() and not card.is_derived and not table.contains(all_names, card.name) then
        table.insert(all_names, card.name)
        local to_use = Fk:cloneCard(card.name)
        to_use:addSubcards(handcards)
        if Self:canUse(to_use) and not Self:prohibitUse(to_use) then
          local x = 0
          if to_use.multiple_targets and to_use.skill:getMinTargetNum() == 0 then
            for _, p in ipairs(Fk:currentRoom().alive_players) do
              if not Self:isProhibited(p, card) and card.skill:modTargetFilter(p.id, {}, Self.id, card, true) then
                x = x + 1
              end
            end
          end
          if x <= Self:getHandcardNum() then
            table.insert(names, card.name)
          end
        end
      end
    end
    if #names == 0 then return end
    return UI.ComboBox {choices = names, all_choices = all_names}
  end,
  card_num = 0,
  min_target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    if self.interaction.data == nil then return false end
    local to_use = Fk:cloneCard(self.interaction.data)
    to_use.skillName = self.name
    to_use:addSubcards(Self:getCardIds(Player.Hand))
    if not to_use.skill:targetFilter(to_select, selected, selected_cards, to_use) then return false end
    if (#selected == 0 or to_use.multiple_targets) and
    Self:isProhibited(Fk:currentRoom():getPlayerById(to_select), to_use) then return false end
    if to_use.multiple_targets then
      if #selected >= Self:getHandcardNum() then return false end
      if to_use.skill:getMaxTargetNum(Self, to_use) == 1 then
        local x = 0
        for _, p in ipairs(Fk:currentRoom().alive_players) do
          if p.id == to_select or (not Self:isProhibited(p, to_use) and to_use.skill:modTargetFilter(p.id, {to_select}, Self.id, to_use, true)) then
            x = x + 1
          end
        end
        if x > Self:getHandcardNum() then return false end
      end
    end
    return true
  end,
  feasible = function(self, selected, selected_cards)
    if self.interaction.data == nil then return false end
    local to_use = Fk:cloneCard(self.interaction.data)
    to_use.skillName = self.name
    to_use:addSubcards(Self:getCardIds(Player.Hand))
    return to_use.skill:feasible(selected, selected_cards, Self, to_use)
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local use = {
      from = player.id,
      tos = table.map(effect.tos, function (id)
        return {id}
      end),
      card = Fk:cloneCard(self.interaction.data),
    }
    use.card:addSubcards(player:getCardIds(Player.Hand))
    use.card.skillName = self.name
    room:useCard(use)
    if not player.dead and player:getMark("@@wk_heg__ld__qice_transform") == 0 and room:askForChoice(player, {"transform_deputy", "Cancel"}, self.name) ~= "Cancel" then
      room:setPlayerMark(player, "@@wk_heg__ld__qice_transform", 1)
      H.transformGeneral(room, player)
    end
  end,
}

local yijiXZ = fk.CreateTriggerSkill{
  name = "wk_heg__hs__yiji",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ids = room:getNCards(2)
    while true do
      room:setPlayerMark(player, "hs__yiji_cards", ids)
      local _, ret = room:askForUseActiveSkill(player, "hs__yiji_active", "#hs__yiji-give", true, nil, true)
      room:setPlayerMark(player, "hs__yiji_cards", 0)
      if ret then
        for _, id in ipairs(ret.cards) do
          table.removeOne(ids, id)
        end
        room:moveCardTo(ret.cards, Card.PlayerHand, room:getPlayerById(ret.targets[1]), fk.ReasonGive, self.name, nil, false, player.id)
        if #ids == 0 then break end
        if player.dead then
          room:moveCards({
            ids = ids,
            toArea = Card.DiscardPile,
            moveReason = fk.ReasonJustMove,
            skillName = self.name,
          })
          break
        end
      else
        room:moveCardTo(ids, Player.Hand, player, fk.ReasonGive, self.name, nil, false, player.id)
        break
      end
    end
  end,
}

local quhuXZ = fk.CreateActiveSkill{
  name = "wk_heg__quhu",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and Self:canPindian(target) and target.hp > Self.hp
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local pindian = player:pindian({target}, self.name)
    if pindian.results[target.id].winner == player then
      local targets = {}
      for _, p in ipairs(room:getOtherPlayers(target)) do
        if target:inMyAttackRange(p) then
          table.insert(targets, p.id)
        end
      end
      if #targets == 0 then return end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#quhu-choose", self.name)
      room:damage{
        from = target,
        to = room:getPlayerById(tos[1]),
        damage = 1,
        skillName = self.name,
      }
    else
      room:damage{
        from = target,
        to = player,
        damage = 1,
        skillName = self.name,
      }
    end
  end,
}

zhongyao:addSkill(chengqi)
zhongyao:addSkill(xunzuo)
zhongyao:addRelatedSkill(choulueXZ)
zhongyao:addRelatedSkill(weimuXZ)
zhongyao:addRelatedSkill(qiceXZ)
zhongyao:addRelatedSkill(yijiXZ)
zhongyao:addRelatedSkill(quhuXZ)
Fk:loadTranslationTable{
  ["wk_heg__zhongyao"] = "钟繇",
  ["designer:wk_heg__zhongyao"] = "教父&静谦&祭祀",
  ["wk_heg__chengqi"] = "承启",
  [":wk_heg__chengqi"] = "当你使用基本牌或普通锦囊牌选择目标后，你可弃置一张黑桃牌，为此牌重新指定至多等量个目标（无视合法性）。",
  ["wk_heg__xunzuo"] = "勋佐",
  [":wk_heg__xunzuo"] = "与你势力相同角色的结束阶段，若其武将牌均明置且其未以此法获得过技能，你可以令其选择并失去武将牌上一个技能，然后其选择并获得下列一个所有角色均没有的技能：遗计，驱虎，帷幕，奇策，筹略。",

  ["#wk_heg__chengqi-choose"] = "承启：你可以弃置一张黑桃牌，为此牌重新指定至多等量个目标",
  ["#wk_heg__xunzuo-choice"] = "勋佐：请选择一个技能获得",

  ["_heg__BattleRoyalMode_ignore"] = "无视鏖战",

  ["wk_heg__hs__yiji"] = "遗计",
  [":wk_heg__hs__yiji"] = "当你受到伤害后，你可观看牌堆顶两张牌，然后你可将这些牌交给任意角色。",
  ["wk_heg__quhu"] = "驱虎", 
  [":wk_heg__quhu"] = "出牌阶段限一次，你可以与一名体力值大于你的角色拼点，若你：赢，你令其对其攻击范围内的一名角色造成1点伤害；没赢，其对你造成1点伤害。", 
  ["wk_heg__hs__weimu"] = "帷幕",
  [":wk_heg__hs__weimu"] = "锁定技，当你成为黑色锦囊牌的目标时，取消之。",
  ["wk_heg__ld__qice"] = "奇策",
  [":wk_heg__ld__qice"] = "出牌阶段限一次，你可以将所有手牌当做一张指定目标数不大于X的任意普通锦囊牌使用（X为你的手牌数），然后你可变更一次副将。",
  ["@@wk_heg__ld__qice_transform"] = "奇策 已变更",
  ["wk_heg__wk_heg__choulue"] = "筹略",
  [":wk_heg__wk_heg__choulue"] = "①当你受到伤害后，若你的“阴阳鱼”标记数小于你体力上限，你可获得一个“阴阳鱼”标记；②与你势力相同的角色使用普通锦囊牌指定唯一目标后，你可移去一个“阴阳鱼”标记，令此牌结算两次。",

  ["@wk_heg__xunzuo"] = "勋佐",
  
  ["$wk_heg__chengqi1"] = "世有十万字形，亦当有十万字体。",
  ["$wk_heg__chengqi2"] = "笔画如骨，不可据于一形。",
  ["$wk_heg__xunzuo1"] = "只有忠心，没有谋略，是不够的",
  ["$wk_heg__xunzuo2"] = "承君恩宠，报效国家。",

  ["~wk_heg__zhongyao"] = "",
}

--]]--
---
return extension
